<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="下面笔记都是使用Windows系统">
<meta property="og:type" content="article">
<meta property="og:title" content="rust学习笔记（1）：Day1 Moring">
<meta property="og:url" content="https://wyatex.online/Rust/rust-note-1-google/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="下面笔记都是使用Windows系统">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-01-02T03:19:15.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:47.239Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Rust">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/Rust/rust-note-1-google/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Rust/rust-note-1-google/","path":"Rust/rust-note-1-google/","title":"rust学习笔记（1）：Day1 Moring"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>rust学习笔记（1）：Day1 Moring | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE"><span class="nav-number">1.</span> <span class="nav-text">环境配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85Rustup"><span class="nav-number">1.1.</span> <span class="nav-text">安装Rustup</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85Mingw"><span class="nav-number">1.2.</span> <span class="nav-text">安装Mingw</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BARust%E9%A1%B9%E7%9B%AE"><span class="nav-number">2.</span> <span class="nav-text">创建Rust项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cargo%E4%BD%BF%E7%94%A8"><span class="nav-number">3.</span> <span class="nav-text">Cargo使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hello-World"><span class="nav-number">4.</span> <span class="nav-text">Hello World</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E7%A4%BA%E4%BE%8B"><span class="nav-number">4.1.</span> <span class="nav-text">简单示例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8Rust"><span class="nav-number">5.</span> <span class="nav-text">为什么使用Rust</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BC%96%E8%AF%91%E6%97%B6%E4%BF%9D%E8%AF%81"><span class="nav-number">5.1.</span> <span class="nav-text">编译时保证</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%90%E8%A1%8C%E6%97%B6%E4%BF%9D%E8%AF%81"><span class="nav-number">5.2.</span> <span class="nav-text">运行时保证</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%8E%B0%E4%BB%A3%E7%89%B9%E6%80%A7"><span class="nav-number">5.3.</span> <span class="nav-text">现代特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%AD%E8%A8%80%E7%89%B9%E6%80%A7"><span class="nav-number">5.4.</span> <span class="nav-text">语言特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B7%A5%E5%85%B7"><span class="nav-number">5.5.</span> <span class="nav-text">工具</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95"><span class="nav-number">6.</span> <span class="nav-text">基础语法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B"><span class="nav-number">6.1.</span> <span class="nav-text">基础类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B"><span class="nav-number">6.2.</span> <span class="nav-text">复合类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%95%E7%94%A8"><span class="nav-number">6.3.</span> <span class="nav-text">引用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%82%AC%E7%A9%BA%E5%BC%95%E7%94%A8"><span class="nav-number">6.3.1.</span> <span class="nav-text">悬空引用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%87%E7%89%87-Slices"><span class="nav-number">6.4.</span> <span class="nav-text">切片&#x2F;Slices</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#String-vs-str"><span class="nav-number">6.4.1.</span> <span class="nav-text">String vs str</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0-Functions"><span class="nav-number">6.5.</span> <span class="nav-text">函数&#x2F;Functions</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95-Methods"><span class="nav-number">6.5.1.</span> <span class="nav-text">方法&#x2F;Methods</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD"><span class="nav-number">6.5.2.</span> <span class="nav-text">函数重载</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%83%E4%B9%A01"><span class="nav-number">7.</span> <span class="nav-text">练习1</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%9A%90%E5%BC%8F%E8%BD%AC%E5%9E%8B"><span class="nav-number">7.1.</span> <span class="nav-text">隐式转型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E5%92%8Cfor%E5%BE%AA%E7%8E%AF"><span class="nav-number">7.2.</span> <span class="nav-text">数组和for循环</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%99%84%E5%8A%A0%E9%A2%98"><span class="nav-number">7.2.1.</span> <span class="nav-text">附加题</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Rust/rust-note-1-google/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="rust学习笔记（1）：Day1 Moring | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          rust学习笔记（1）：Day1 Moring
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-01-02 11:19:15" itemprop="dateCreated datePublished" datetime="2023-01-02T11:19:15+08:00">2023-01-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:47" itemprop="dateModified" datetime="2023-05-05T09:25:47+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Rust/" itemprop="url" rel="index"><span itemprop="name">Rust</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>下面笔记都是使用Windows系统</p>
<span id="more"></span>

<h2 id="环境配置"><a href="#环境配置" class="headerlink" title="环境配置"></a>环境配置</h2><p>首先需要安装Rustup和mingw-w64，其中Rustup用于安装Rust编译器和Cargo，编译出可执行文件还需要mingw-w64进行连接，当然如果你的电脑有装VS而且装msvc编译工具，也可以不使用mingw。</p>
<h3 id="安装Rustup"><a href="#安装Rustup" class="headerlink" title="安装Rustup"></a>安装Rustup</h3><p>如果你的系统已经安装了Chocolatey 或者 Scoop,可以使用他们安装Rustup，我就为了方便就用系统自带的Winget来安装了：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">winget install rustup</span><br></pre></td></tr></table></figure>

<p>然后安装工具链的话，如果你的电脑有msvc，就下使用msvc的工具链：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rustup toolchain install stable-x86_64-pc-windows-msvc</span><br></pre></td></tr></table></figure>

<p>如果你的电脑没有msvc，推荐使用mingw，更加小巧而且安装方便：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rustup toolchain install stable-x86_64-pc-windows-gnu</span><br></pre></td></tr></table></figure>

<p>工具链也可以安装多个，可以用下面的方法切换：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># 切到mingw</span><br><span class="line">rustup default stable-x86_64-pc-windows-gnu</span><br><span class="line"># 切到msvc</span><br><span class="line">rustup default stable-x86_64-pc-windows-msvc</span><br></pre></td></tr></table></figure>

<h3 id="安装Mingw"><a href="#安装Mingw" class="headerlink" title="安装Mingw"></a>安装Mingw</h3><p>如果你的电脑没有msvc，可以选择安装mingw，当然你要装msvc也可以，但是因为我是使用mingw所以下面教程都是使用mingw。</p>
<p>打开<a target="_blank" rel="noopener" href="https://github.com/niXman/mingw-builds-binaries/releases">mingw的github release页面</a>，选择最新的版本，比如写这篇笔记时最新是12.2.0，那么我们可以点击Assets下面的：<code>x86_64-12.2.0-release-posix-seh-msvcrt-rt_v10-rev2.7z</code> 进行下载。</p>
<p>下载完成后我们可以找个位置存放，比如我放到了：<code>E:\Program Files\mingw64</code></p>
<p>然后打开环境变量配置，在Path加入：<code>E:\Program Files\mingw64\bin</code> 别漏掉最后面的bin目录哦</p>
<h2 id="创建Rust项目"><a href="#创建Rust项目" class="headerlink" title="创建Rust项目"></a>创建Rust项目</h2><p>我使用的是Clion加Rust插件，当然如果没有买jetbrains产品的话也可以使用Idea社区版然后安装rust插件。</p>
<p>安装完Rust插件之后，新建项目就会有Rust选项，选择工具链位置，如果已经弹出来那就可以不用自己手选，如果是没有的话，应该是在：<code>C:\Users\你的用户名\.cargo\bin</code></p>
<p>下面有个标准库不知道有没有用，反正我点了下面的下载按钮之后就弹出来了。</p>
<p>创建完成后项目有一个main.rs：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;Hello, world!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>点击运行成功打印：<code>Hello, world!</code></p>
<h2 id="Cargo使用"><a href="#Cargo使用" class="headerlink" title="Cargo使用"></a>Cargo使用</h2><p>如果在终端运行的话，只需要执行：<code>cargo run</code></p>
<p>如果需要构建可执行文件只需要：<code>cargo build</code>，如果需要优化可执行文件就加上选项：<code>cargo build --release</code></p>
<h2 id="Hello-World"><a href="#Hello-World" class="headerlink" title="Hello World"></a>Hello World</h2><p>首先看看上面提到的代码：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;Hello 🌍!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>函数通过fn引入。</li>
<li>像在C和c++中一样，块由花括号分隔。</li>
<li>main函数是程序的入口点。</li>
<li>Rust有卫生宏，<code>println!</code>就是一个例子。</li>
<li>Rust字符串是UTF-8编码的，可以包含任何Unicode字符。</li>
</ul>
<h3 id="简单示例"><a href="#简单示例" class="headerlink" title="简单示例"></a>简单示例</h3><figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;              <span class="comment">// 程序入口</span></span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">x</span>: <span class="type">i32</span> = <span class="number">6</span>;  <span class="comment">// 可变变量绑定</span></span><br><span class="line">    <span class="built_in">print!</span>(<span class="string">&quot;&#123;x&#125;&quot;</span>);       <span class="comment">// 使用宏打印，类似printf</span></span><br><span class="line">    <span class="keyword">while</span> x != <span class="number">1</span> &#123;       <span class="comment">// 表达式不需要圆括号</span></span><br><span class="line">        <span class="keyword">if</span> x % <span class="number">2</span> == <span class="number">0</span> &#123;  <span class="comment">// 像其他语言一样进行数学运算</span></span><br><span class="line">            x = x / <span class="number">2</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            x = <span class="number">3</span> * x + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">print!</span>(<span class="string">&quot; -&gt; &#123;x&#125;&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">println!</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="为什么使用Rust"><a href="#为什么使用Rust" class="headerlink" title="为什么使用Rust"></a>为什么使用Rust</h2><ul>
<li>编译时内存安全。</li>
<li>缺乏未定义的运行时行为。</li>
<li>现代语言特征。</li>
</ul>
<h3 id="编译时保证"><a href="#编译时保证" class="headerlink" title="编译时保证"></a>编译时保证</h3><p>编译时的静态内存管理：</p>
<ul>
<li>没有未初始化的变量。</li>
<li>基本上没有内存泄漏。</li>
<li>没有double-frees。</li>
<li>没有use-after-free。</li>
<li>没有空指针。</li>
<li>没有被遗忘的锁定互斥对象。</li>
<li>线程之间没有数据争用。</li>
<li>没有迭代器失效。</li>
</ul>
<p>从技术上讲，在(安全的)Rust中产生内存泄漏是可能的。<code>Box::leak</code>方法允许从Box中获取原始引用，然后在不运行析构函数的情况下删除Box。这可以用于获得运行时初始化和运行时大小的静态变量。或者简单地说，<code>std::mem::forget</code>函数，它使编译器忘记一个值，这意味着析构函数永远不会运行。在安全的Rust中有许多其他的方法来创建泄漏，但是为了本课程的目的，没有内存泄漏应该被理解为几乎没有意外的内存泄漏。</p>
<h3 id="运行时保证"><a href="#运行时保证" class="headerlink" title="运行时保证"></a>运行时保证</h3><p>运行时没有未定义的行为:</p>
<ul>
<li>数组访问是边界检查。</li>
<li>定义了整数溢出。</li>
</ul>
<h3 id="现代特性"><a href="#现代特性" class="headerlink" title="现代特性"></a>现代特性</h3><p>Rust是在过去40年里积累的经验。</p>
<h3 id="语言特性"><a href="#语言特性" class="headerlink" title="语言特性"></a>语言特性</h3><ul>
<li>枚举和模式匹配。</li>
<li>泛型。</li>
<li>没有开销的FFI。</li>
</ul>
<h3 id="工具"><a href="#工具" class="headerlink" title="工具"></a>工具</h3><ul>
<li>非常良好的编译器错误提示。</li>
<li>内置依赖管理器。</li>
<li>内置测试支持。</li>
</ul>
<h2 id="基础语法"><a href="#基础语法" class="headerlink" title="基础语法"></a>基础语法</h2><p>Rust的很多语法对您来说都是熟悉的C或c++语法：</p>
<ul>
<li>块和范围由花括号分隔。</li>
<li>行注释使用 <code>//</code> 开始，块注释使用： <code>/* ... */</code></li>
<li>关键字如if和while的作用相同。</li>
<li>变量赋值用<code>=</code>，比较用<code>==</code>。</li>
</ul>
<h3 id="基础类型"><a href="#基础类型" class="headerlink" title="基础类型"></a>基础类型</h3><table>
<thead>
<tr>
<th>分类</th>
<th>类型</th>
<th>字面量</th>
</tr>
</thead>
<tbody><tr>
<td>带符号整数</td>
<td>i8, i16, i32, i64, i128, isize</td>
<td>-10, 0, 1_000, 123i64</td>
</tr>
<tr>
<td>无符号整数</td>
<td>u8, u16, u32, u64, u128, usize</td>
<td>0, 123, 10u16</td>
</tr>
<tr>
<td>浮点数</td>
<td>f32, f64</td>
<td>3.14, -10.0e20, 2f32</td>
</tr>
<tr>
<td>字符串</td>
<td>&amp;str</td>
<td>“foo”, <code>r#&quot;\\&quot;#</code></td>
</tr>
<tr>
<td>Unicode标量值</td>
<td>char</td>
<td>‘a’, ‘α’, ‘∞’</td>
</tr>
<tr>
<td>字节字符串</td>
<td><code>&amp;[u8]</code></td>
<td>b”abc”, <code>br#&quot; &quot; &quot;#</code></td>
</tr>
<tr>
<td>布尔值</td>
<td>bool</td>
<td>true, false</td>
</tr>
</tbody></table>
<p>类型的宽度如下所示：</p>
<ul>
<li>iN、uN和fN的宽度为N位</li>
<li>isize 和 usize 是指针的宽度</li>
<li>char 是 32 位宽</li>
<li>bool 是 8 位宽</li>
</ul>
<h3 id="复合类型"><a href="#复合类型" class="headerlink" title="复合类型"></a>复合类型</h3><table>
<thead>
<tr>
<th>分类</th>
<th>类型</th>
<th>字面量</th>
</tr>
</thead>
<tbody><tr>
<td>数组</td>
<td>[T; N]</td>
<td>[20, 30, 40], [0; 3]</td>
</tr>
<tr>
<td>元组</td>
<td>(T1, T2, T3, …)</td>
<td>(‘x’, 1.2, 0)</td>
</tr>
</tbody></table>
<p>数组分配和访问:</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">a</span>: [<span class="type">i8</span>; <span class="number">10</span>] = [<span class="number">42</span>; <span class="number">10</span>];</span><br><span class="line">    a[<span class="number">5</span>] = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;a: &#123;:?&#125;&quot;</span>, a);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>元组分配和访问:</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">t</span>: (<span class="type">i8</span>, <span class="type">bool</span>) = (<span class="number">7</span>, <span class="literal">true</span>);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;1st index: &#123;&#125;&quot;</span>, t.<span class="number">0</span>);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;2nd index: &#123;&#125;&quot;</span>, t.<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h3><p>类似C++，Rust这样引用：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">x</span>: <span class="type">i32</span> = <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">ref_x</span>: &amp;<span class="keyword">mut</span> <span class="type">i32</span> = &amp;<span class="keyword">mut</span> x;</span><br><span class="line">    *ref_x = <span class="number">20</span>;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;x: &#123;x&#125;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>和C++不一样的地方：</p>
<ul>
<li>在给<code>ref_x</code>赋值时，我们必须解引用它，类似于C指针</li>
<li>Rust在某些情况下会自动解引用，特别是在调用方法时(尝试<code>count_ones</code>)。</li>
</ul>
<h4 id="悬空引用"><a href="#悬空引用" class="headerlink" title="悬空引用"></a>悬空引用</h4><p>Rust将静态禁止悬空引用</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">ref_x</span>: &amp;<span class="type">i32</span>;</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">let</span> <span class="variable">x</span>: <span class="type">i32</span> = <span class="number">10</span>;</span><br><span class="line">        ref_x = &amp;x; <span class="comment">// 报错：borrowed value does not live long enough</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;ref_x: &#123;ref_x&#125;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>引用被称为借用它所引用的值。</li>
<li>Rust正在跟踪所有引用的生命周期，以确保它们的生存时间足够长。</li>
<li>当我们讲到所有权时，我们会更多地讨论借用。</li>
</ul>
<h3 id="切片-Slices"><a href="#切片-Slices" class="headerlink" title="切片&#x2F;Slices"></a>切片&#x2F;Slices</h3><p>切片为您提供了一个更大集合的视图</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">a</span>: [<span class="type">i32</span>; <span class="number">6</span>] = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>, <span class="number">60</span>];</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;a: &#123;a:?&#125;&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">s</span>: &amp;[<span class="type">i32</span>] = &amp;a[<span class="number">2</span>..<span class="number">4</span>];</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;s: &#123;s:?&#125;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>切片从切片类型中借用数据</li>
<li>提问:如果修改<code>a[3]</code>会怎样</li>
</ul>
<h4 id="String-vs-str"><a href="#String-vs-str" class="headerlink" title="String vs str"></a>String vs str</h4><p>现在我们可以这样理解Rust中的两种字符串类型:</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">s1</span>: &amp;<span class="type">str</span> = <span class="string">&quot;Hello&quot;</span>;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;s1: &#123;s1&#125;&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">s2</span>: <span class="type">String</span> = <span class="type">String</span>::<span class="title function_ invoke__">from</span>(<span class="string">&quot;Hello &quot;</span>);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;s2: &#123;s2&#125;&quot;</span>);</span><br><span class="line">    s2.<span class="title function_ invoke__">push_str</span>(s1);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;s2: &#123;s2&#125;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Rust 术语：</p>
<ul>
<li><code>&amp;str</code>是对字符串片的不可变引用。</li>
<li><code>String</code>是可变字符串缓冲区。</li>
</ul>
<h3 id="函数-Functions"><a href="#函数-Functions" class="headerlink" title="函数&#x2F;Functions"></a>函数&#x2F;Functions</h3><p>Rust版的著名的<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Fizz_buzz">FizzBuzz</a>面试问题：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="title function_ invoke__">fizzbuzz_to</span>(<span class="number">20</span>);   <span class="comment">// 在下面定义，不需要在前面声明</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">is_divisible_by</span>(lhs: <span class="type">u32</span>, rhs: <span class="type">u32</span>) <span class="punctuation">-&gt;</span> <span class="type">bool</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> rhs == <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;  <span class="comment">// 边界情况，提前返回</span></span><br><span class="line">    &#125;</span><br><span class="line">    lhs % rhs == <span class="number">0</span>     <span class="comment">// 最后一个表达式是返回值</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">fizzbuzz</span>(n: <span class="type">u32</span>) <span class="punctuation">-&gt;</span> () &#123;  <span class="comment">// 没有返回值意味着返回单元类型 `()`</span></span><br><span class="line">    <span class="keyword">match</span> (<span class="title function_ invoke__">is_divisible_by</span>(n, <span class="number">3</span>), <span class="title function_ invoke__">is_divisible_by</span>(n, <span class="number">5</span>)) &#123;</span><br><span class="line">        (<span class="literal">true</span>,  <span class="literal">true</span>)  =&gt; <span class="built_in">println!</span>(<span class="string">&quot;fizzbuzz&quot;</span>),</span><br><span class="line">        (<span class="literal">true</span>,  <span class="literal">false</span>) =&gt; <span class="built_in">println!</span>(<span class="string">&quot;fizz&quot;</span>),</span><br><span class="line">        (<span class="literal">false</span>, <span class="literal">true</span>)  =&gt; <span class="built_in">println!</span>(<span class="string">&quot;buzz&quot;</span>),</span><br><span class="line">        (<span class="literal">false</span>, <span class="literal">false</span>) =&gt; <span class="built_in">println!</span>(<span class="string">&quot;&#123;n&#125;&quot;</span>),</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">fizzbuzz_to</span>(n: <span class="type">u32</span>) &#123;  <span class="comment">// `-&gt; ()` 通常省略</span></span><br><span class="line">    <span class="keyword">for</span> <span class="variable">n</span> <span class="keyword">in</span> <span class="number">1</span>..=n &#123;</span><br><span class="line">        <span class="title function_ invoke__">fizzbuzz</span>(n);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="方法-Methods"><a href="#方法-Methods" class="headerlink" title="方法&#x2F;Methods"></a>方法&#x2F;Methods</h4><p>Rust有方法，它们只是与特定类型相关联的函数。方法的第一个参数是与其关联的类型的实例：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Rectangle</span> &#123;</span><br><span class="line">    width: <span class="type">u32</span>,</span><br><span class="line">    height: <span class="type">u32</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">impl</span> <span class="title class_">Rectangle</span> &#123;</span><br><span class="line">    <span class="keyword">fn</span> <span class="title function_">area</span>(&amp;<span class="keyword">self</span>) <span class="punctuation">-&gt;</span> <span class="type">u32</span> &#123;</span><br><span class="line">        <span class="keyword">self</span>.width * <span class="keyword">self</span>.height</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">fn</span> <span class="title function_">inc_width</span>(&amp;<span class="keyword">mut</span> <span class="keyword">self</span>, delta: <span class="type">u32</span>) &#123;</span><br><span class="line">        <span class="keyword">self</span>.width += delta;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">rect</span> = Rectangle &#123; width: <span class="number">10</span>, height: <span class="number">5</span> &#125;;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;old area: &#123;&#125;&quot;</span>, rect.<span class="title function_ invoke__">area</span>());</span><br><span class="line">    rect.<span class="title function_ invoke__">inc_width</span>(<span class="number">5</span>);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;new area: &#123;&#125;&quot;</span>, rect.<span class="title function_ invoke__">area</span>());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="函数重载"><a href="#函数重载" class="headerlink" title="函数重载"></a>函数重载</h4><p>Rust不支持重载:</p>
<ul>
<li>每个函数都只有一个实现:<ul>
<li>总是接受固定数量的参数。</li>
<li>始终接受一组参数类型。</li>
</ul>
</li>
<li>不支持默认值:<ul>
<li>所有调用的地方的参数个数相同。</li>
<li>宏有时被用作一种替代方法。</li>
</ul>
</li>
</ul>
<p>然而，函数参数可以是通用的：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">pick_one</span>&lt;T&gt;(a: T, b: T) <span class="punctuation">-&gt;</span> T &#123;</span><br><span class="line">    <span class="keyword">if</span> std::process::<span class="title function_ invoke__">id</span>() % <span class="number">2</span> == <span class="number">0</span> &#123; a &#125; <span class="keyword">else</span> &#123; b &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;coin toss: &#123;&#125;&quot;</span>, <span class="title function_ invoke__">pick_one</span>(<span class="string">&quot;heads&quot;</span>, <span class="string">&quot;tails&quot;</span>));</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;cash prize: &#123;&#125;&quot;</span>, <span class="title function_ invoke__">pick_one</span>(<span class="number">500</span>, <span class="number">1000</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="练习1"><a href="#练习1" class="headerlink" title="练习1"></a>练习1</h2><p>在这些练习中，我们将探索Rust的两个部分:</p>
<ul>
<li>类型之间的隐式转换。</li>
<li>数组和 for 循环。</li>
</ul>
<h3 id="隐式转型"><a href="#隐式转型" class="headerlink" title="隐式转型"></a>隐式转型</h3><p>Rust不会自动进行类型之间的隐式转换(与c++不同)。你可以在这样的程序中看到这一点：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">multiply</span>(x: <span class="type">i16</span>, y: <span class="type">i16</span>) <span class="punctuation">-&gt;</span> <span class="type">i16</span> &#123;</span><br><span class="line">    x * y</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">x</span>: <span class="type">i8</span> = <span class="number">15</span>;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">y</span>: <span class="type">i16</span> = <span class="number">1000</span>;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;&#123;x&#125; * &#123;y&#125; = &#123;&#125;&quot;</span>, <span class="title function_ invoke__">multiply</span>(x, y));</span><br><span class="line">                                     <span class="comment">// ^  expected `i16`, found `i8`</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Rust整数类型都实现了<code>From&lt;T&gt;</code>和<code>Into&lt;T&gt;</code>traits(翻译：特性)，以便我们在它们之间进行转换。<code>From&lt;T&gt;</code> trait有一个<code>From()</code>方法，类似地，<code>Into&lt;T&gt;</code> trait有一个<code>Into()</code>方法。实现这些特征是一种类型表示它可以转换为另一种类型的方式。</p>
<p>标准库有一个用于<code>i16</code>的<code>From&lt;i8&gt;</code>实现，这意味着我们可以通过调用<code>i16::from(x)</code>将类型为<code>i8</code>的变量x转换为<code>i16</code>。或者，更简单一点，使用<code>x.into()</code>，因为i16实现的<code>From&lt;i8&gt;</code>会自动为<code>i8</code>创建<code>Into&lt;i16&gt;</code>的实现。</p>
<ol>
<li>执行上面的程序并查看编译器错误。(报错我在上面标出来了)</li>
<li>更新上面的代码以使用<code>into()</code>进行转换。</li>
<li>将x和y的类型更改为其他类型(例如f32, bool, i128)，以查看哪些类型可以转换为其他类型。尝试将小类型转换为大类型，或者反过来转换。检查<a target="_blank" rel="noopener" href="https://doc.rust-lang.org/std/convert/trait.From.html">标准库文档</a>，查看是否为您检查的对实现了<code>From&lt;T&gt;</code>。</li>
</ol>
<h3 id="数组和for循环"><a href="#数组和for循环" class="headerlink" title="数组和for循环"></a>数组和for循环</h3><p>我们看到数组可以这样声明:</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="variable">array</span> = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>];</span><br></pre></td></tr></table></figure>

<p>你可以通过 <code>&#123;:?&#125;</code> 来打印数组:</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">array</span> = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>];</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;array: &#123;array:?&#125;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Rust允许您使用<code>for</code>关键字迭代数组和范围等内容：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">array</span> = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>];</span><br><span class="line">    <span class="built_in">print!</span>(<span class="string">&quot;Iterating over array:&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span> <span class="variable">n</span> <span class="keyword">in</span> array &#123;</span><br><span class="line">        <span class="built_in">print!</span>(<span class="string">&quot; &#123;n&#125;&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">println!</span>();</span><br><span class="line"></span><br><span class="line">    <span class="built_in">print!</span>(<span class="string">&quot;Iterating over range:&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span> <span class="variable">i</span> <span class="keyword">in</span> <span class="number">0</span>..<span class="number">3</span> &#123;</span><br><span class="line">        <span class="built_in">print!</span>(<span class="string">&quot; &#123;&#125;&quot;</span>, array[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">println!</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用上面的方法来写一个函数<code>pretty_print</code>，它可以漂亮地打印一个矩阵，以及一个函数transpose，它将转置一个矩阵(将行转换为列)。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">| <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> |    | <span class="number">1</span> <span class="number">4</span> <span class="number">7</span> |</span><br><span class="line">| <span class="number">4</span> <span class="number">5</span> <span class="number">6</span> | =&gt; | <span class="number">2</span> <span class="number">5</span> <span class="number">8</span> |</span><br><span class="line">| <span class="number">7</span> <span class="number">8</span> <span class="number">9</span> |    | <span class="number">3</span> <span class="number">6</span> <span class="number">9</span> |</span><br></pre></td></tr></table></figure>

<p>硬编码两个函数操作3x3矩阵。</p>
<p>复制下面的代码到 <a target="_blank" rel="noopener" href="https://play.rust-lang.org/">https://play.rust-lang.org/</a> 并且实现功能</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// <span class="doctag">TODO:</span> 在完成实现后删除它。</span></span><br><span class="line"><span class="meta">#![allow(unused_variables, dead_code)]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">transpose</span>(matrix: [[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>]) <span class="punctuation">-&gt;</span> [[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>] &#123;</span><br><span class="line">    <span class="built_in">unimplemented!</span>()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">pretty_print</span>(matrix: &amp;[[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>]) &#123;</span><br><span class="line">    <span class="built_in">unimplemented!</span>()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">matrix</span> = [</span><br><span class="line">        [<span class="number">101</span>, <span class="number">102</span>, <span class="number">103</span>], <span class="comment">// &lt;-- 该注释保证rustfmt让代码换行</span></span><br><span class="line">        [<span class="number">201</span>, <span class="number">202</span>, <span class="number">203</span>],</span><br><span class="line">        [<span class="number">301</span>, <span class="number">302</span>, <span class="number">303</span>],</span><br><span class="line">    ];</span><br><span class="line"></span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;matrix:&quot;</span>);</span><br><span class="line">    <span class="title function_ invoke__">pretty_print</span>(&amp;matrix);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">transposed</span> = <span class="title function_ invoke__">transpose</span>(matrix);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;transposed:&quot;</span>);</span><br><span class="line">    <span class="title function_ invoke__">pretty_print</span>(&amp;transposed);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是我的作业答案，聪明的小伙伴可以看看有没有值得改进的地方：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">transpose</span>(matrix: [[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>]) <span class="punctuation">-&gt;</span> [[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>] &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">new_matrix</span>: [[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>] = [[<span class="number">0</span>; <span class="number">3</span>]; <span class="number">3</span>];</span><br><span class="line">    <span class="keyword">for</span> <span class="variable">i</span> <span class="keyword">in</span> <span class="number">0</span>..<span class="number">3</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> <span class="variable">j</span> <span class="keyword">in</span> <span class="number">0</span>..<span class="number">3</span> &#123;</span><br><span class="line">            new_matrix[j][i] = matrix[i][j]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    new_matrix</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">pretty_print</span>(matrix: &amp;[[<span class="type">i32</span>; <span class="number">3</span>]; <span class="number">3</span>]) &#123;</span><br><span class="line">    <span class="keyword">for</span> <span class="variable">i</span> <span class="keyword">in</span> <span class="number">0</span>..<span class="number">3</span> &#123;</span><br><span class="line">        <span class="built_in">print!</span>(<span class="string">&quot;|&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> <span class="variable">j</span> <span class="keyword">in</span> <span class="number">0</span>..<span class="number">3</span> &#123;</span><br><span class="line">            <span class="built_in">print!</span>(<span class="string">&quot; &#123;&#125; &quot;</span>, matrix[i][j])</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">println!</span>(<span class="string">&quot;|&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="附加题"><a href="#附加题" class="headerlink" title="附加题"></a>附加题</h4><p>你可以使用<code>&amp;[i32]</code>片代替硬编码的 3 x 3 矩阵作为参数和返回类型吗?对于二维片中的片，类似于<code>&amp;[&amp;[i32]]</code>。为什么或为什么不?</p>
<p>有关生产质量实现，请参阅<a target="_blank" rel="noopener" href="https://docs.rs/ndarray/"><code>ndarray</code> crate</a>。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Rust/rust-note-1-google/" title="rust学习笔记（1）：Day1 Moring">https://wyatex.online/Rust/rust-note-1-google/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/Rust/" rel="tag"># Rust</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/CPP/cpp%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%881%EF%BC%89/" rel="prev" title="C++学习笔记（1）">
                  <i class="fa fa-angle-left"></i> C++学习笔记（1）
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Rust/rust-note-2-google/" rel="next" title="rust学习笔记（2）：Day1 Afternoon">
                  rust学习笔记（2）：Day1 Afternoon <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
